import sys

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import QTimer, QFile, QTextStream
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog

from Login import LoginDialog
from RightIconDelegate import RightIconDelegate
from ui.main_window import Ui_MainWindow  # 导入由qdesigner生成的UI类
from view.data_import_view import DataImportTableView
from view.database_view import DatabaseView
from view.jiekadalao_view import JieKaDaLao


class TreeWidgetDelegate(QtWidgets.QStyledItemDelegate):
    """
    自定义代理，用于在树节点右侧绘制箭头图标
    """
    def __init__(self, parent=None):
        super().__init__(parent)
        # 加载箭头图标
        self.arrow_right = QtGui.QIcon(":/icons/pictures/Expand2.png")
        self.arrow_down = QtGui.QIcon(":/icons/pictures/Fold2.png")

    def paint(self, painter, option, index):
        """
        绘制树节点，包括右侧的箭头图标
        """
        # 先绘制默认的项
        super().paint(painter, option, index)
        
        # 获取项的数据
        item = self.parent().itemFromIndex(index)
        
        # 只对有子项的节点绘制箭头
        if item and item.childCount() > 0:
            # 设置图标大小
            icon_size = QtCore.QSize(13, 13)
            
            # 根据项的展开状态选择图标
            if item.isExpanded():
                icon = self.arrow_down
            else:
                icon = self.arrow_right
                
            # 计算图标位置（右侧）
            rect = option.rect
            icon_rect = QtCore.QRect(
                rect.right() - icon_size.width() - 5,  # 右边距5像素
                rect.top() + (rect.height() - icon_size.height()) // 2,  # 垂直居中
                icon_size.width(),
                icon_size.height()
            )
            
            # 绘制图标
            icon.paint(painter, icon_rect)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setup_tree_widget()
        self.init_connections()
        self.add_database_view()
        self.add_data_import_view()
        self.add_jiekadalao_view()
        # self.init_history_line_edit_field_name()

    def setup_tree_widget(self):
        """
        设置树控件的自定义样式和行为
        """
        # 启用动画效果
        self.ui.treeWidget.setAnimated(True)
        # 禁用双击展开，避免与单击事件冲突
        self.ui.treeWidget.setExpandsOnDoubleClick(False)
        
        # 设置自定义代理来绘制箭头图标
        self.tree_delegate = TreeWidgetDelegate(self.ui.treeWidget)
        self.ui.treeWidget.setItemDelegate(self.tree_delegate)
        
        # 连接项展开和折叠信号，用于更新箭头图标
        self.ui.treeWidget.itemExpanded.connect(self.on_item_state_changed)
        self.ui.treeWidget.itemCollapsed.connect(self.on_item_state_changed)

    def on_item_state_changed(self, item):
        """
        当项展开或折叠时触发，用于更新界面显示
        """
        # 这个方法会在项状态改变时被调用，确保界面刷新
        pass

    # 初始化控件
    def init_connections(self):
        self.ui.treeWidget.itemClicked.connect(self.on_item_clicked)  # 连接点击信号

        self.setWindowTitle('深井修井力学计算及钻杆优化')
        self.setGeometry(900, 250, 1440, 900)

        self.ui.treeWidget.setCurrentItem(self.ui.treeWidget.topLevelItem(0))

        self.ui.stackedWidget.setCurrentWidget(self.ui.DB_page_1)
        # self.ui.splitter.setSizes([50, 1])

    # 处理QTreeWidget的点击事件
    def on_item_clicked(self, item, column):
        """
        处理QTreeWidget的点击事件，切换QStackedWidget的页面
        :param item: 被点击的QTreeWidgetItem
        :param column: 被点击的列
        """
        # 如果点击的是有子项的菜单，则只展开/折叠，不切换页面
        if item.childCount() > 0:
            # 切换当前项的展开状态（带动画效果）
            item.setExpanded(not item.isExpanded())
            return

        # 假设QTreeWidget的项和QStackedWidget的页面是一一对应的
        # 可以通过项的文本或索引来获取对应的页面索引
        item_text = item.text(column)
        page_index = self.get_page_index(item_text)
        if page_index is not None:
            self.ui.stackedWidget.setCurrentIndex(page_index)
            self.ui.Page_Name_label.setText(item_text)

    def get_page_index(self, item_text):
        """
        根据QTreeWidget项的文本获取对应的QStackedWidget页面索引
        这里需要根据实际的导航项和页面对应关系进行实现
        """
        # 简单示例，假设导航项文本和页面索引顺序一致
        item_list = []
        self.get_all_items(self.ui.treeWidget.invisibleRootItem(), item_list)
        try:
            return item_list.index(item_text)
        except ValueError:
            return None

    def get_all_items(self, parent_item, item_list):
        """
        递归获取QTreeWidget的所有项的文本
        """
        for row in range(parent_item.childCount()):
            child_item = parent_item.child(row)
            item_list.append(child_item.text(0))
            self.get_all_items(child_item, item_list)

    # 添加数据库视图
    def add_database_view(self):
        self.db_view = DatabaseView(self.ui)

    # 添加数据导入视图
    def add_data_import_view(self):
        self.data_import_view = DataImportTableView(self.ui)

    # 添加解卡打捞视图
    def add_jiekadalao_view(self):
        self.jiekadalao_view = JieKaDaLao(self)

    # def init_history_line_edit_field_name(self):
    #     # 钻柱设计
    #     self.ui.lineEdit_jsD.set_field_name('lineEdit_jsD')
    #     self.ui.lineEdit_aqxs.set_field_name('lineEdit_aqxs')
    #     self.ui.lineEdit_gcmd.set_field_name('lineEdit_gcmd')
    #     self.ui.lineEdit_klaqxs.set_field_name('lineEdit_klaqxs')
    #     self.ui.lineEdit_mcxs.set_field_name('lineEdit_mcxs')
    #     self.ui.lineEdit_xjymd.set_field_name('lineEdit_xjymd')
    #     # 卡点计算
    #     self.ui.lineEdit_stll.set_field_name('lineEdit_stll')
    #     self.ui.lineEdit_zjscd.set_field_name('lineEdit_zjscd')
    #     self.ui.lineEdit_bkwtjmj.set_field_name('lineEdit_bkwtjmj')
    #     # 中和点计算
    #     self.ui.lineEdit_stll_2.set_field_name('lineEdit_stll')
    #     self.ui.lineEdit_xjymd_2.set_field_name('lineEdit_xjymd')
    #     self.ui.lineEdit_gcmd_2.set_field_name('lineEdit_gcmd')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 创建并显示登录对话框
    # login_dialog = LoginDialog()
    # if login_dialog.exec_() == QDialog.Accepted:
    file = QFile(":/styles/ui/style.qss")
    if file.open(QFile.ReadOnly | QFile.Text):
        app.setStyleSheet(QTextStream(file).readAll())
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
    # else:
    #     # 登录取消或失败，退出应用程序
    #     sys.exit(0)